<route>{meta: {title: 'excel读取'}}</route>
<template>
  <Page>
    <Condition>
      <el-form inline ref="form" :model="data" label-width="90px" :rules="rules">
        <el-form-item label="文件路径" prop="filePath">
          <el-button @click="selectFile" type="primary">选择项目文件路径</el-button>
          {{data.filePath}}
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="readFile">确定</el-button>
        </el-form-item>
      </el-form>
    </Condition>
    <DataGrid :data="list" v-if="columns.length > 0">
      <Column v-for="col in columns" :key="col.key" :label="col.value" :prop="col.name"></Column>
    </DataGrid>
  </Page>
</template>

<script>
import Page from '@/components/Page';
import { ipcRenderer } from 'electron';
import Scrollbar from '@/components/Scrollbar';
import DataGrid from '@/components/DataGrid';
import file from '@/native/file';
import Condition from '@/components/Condition';
import dialog from '@/util/dialog';
import Column from '@/components/Column';

/**
 Author: 蒋鑫强
 Time: 2023/6/6
 Description:
 */
export default {
  name: "excelRead",
  components: {Column, Condition, DataGrid, Scrollbar, Page},
  data() {
    return {
      data: {
        filePath: ''
      },

      columns: [],
      list: [],

      rules: {
        filePath: [{required: true,message: '请选择excel文件',trigger: 'blur'}]
      }
    }
  },

  methods: {
    selectFile() {
      ipcRenderer.send('open-file-dialog', {
        filters:[{ name: 'Excel', extensions: ['xlsx', 'xls'] }]
      });
      ipcRenderer.on('get-file-dialog', (event, path) => {
        this.data.filePath = path[0];
      });
    },

    readFile() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const list = file.readExcel(this.data.filePath);
          if (list.length <= 0) {
            dialog.error('文件无内容!');
          } else {
            this.columns = list.splice(0, 1)[0].map((d, index) => {
              return {
                name: `key${index}`,
                value: d
              };
            });
            this.list = list.map(d => {
              const result = {};
              d.forEach((value, index) => {
                result[`key${index}`] = value;
              });
              return result;
            });
            this.afterAction();
          }
        }
      });
    },

    afterAction() {
      //读取之后要做的事情
    }
  }
}
</script>

<style lang="less" scoped>

</style>
